package com.stms.action;

import com.alibaba.fastjson.JSONObject;
import com.stms.pojo.SendClient;
import com.stms.service.ReceiveClientService;
import com.stms.service.SendClientService;
import com.stms.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@CrossOrigin
@RestController
@RequestMapping("/client")
public class ClientController {
    @Autowired
    private SendClientService sendClientService;

    private Integer count;

    @PostMapping("/addSendClient")
    public Result addSendClient(@RequestBody SendClient client) {
        if(sendClientService.addSendClient(client)) {
            return new Result(200, "add success");
        }else{
            return new Result(500, "add fail");
        }
    }

    @PostMapping("/editSendClient")
    public Result editSendClient(@RequestBody SendClient client){
        if(sendClientService.editSendClient(client)) {
            return new Result(200, "edit success");
        }else{
            return new Result(500, "edit fail");
        }
    }

    @PostMapping("/deleteBatch")
    public Result deleteBatch(@RequestBody JSONObject obj){
        try{
            String clientIds = (String)obj.get("clientIds");
            sendClientService.deleteBatch(clientIds);
            return new Result(200, "delete success");
        }catch(Exception e){
            e.printStackTrace();
            return new Result(500, "error");
        }
    }

    @PostMapping("/findByName")
    public Map findByName(String name){
        Map<String,Object> map = new HashMap<>();
        SendClient sendName = sendClientService.findByName(name);
        map.put("sendName",sendName);
        return map;
    }

    @PostMapping("/fuzzyQuery")
    public Map fuzzyQuery(Integer pageNum, Integer pageSize, String direction, SendClient client){
        Page<SendClient> page = sendClientService.fuzzyQuery(pageNum,pageSize,direction,client);
        Map<String,Object> map = new HashMap<>();
        map.put("data",page);
        return map;
    }

    @RequestMapping("/findByPage")
    public Map findByPage(Integer pageNum, Integer pageSize){
        if(count!=null&&pageNum>=count){
            pageNum=count;
        }

        Page<SendClient> bypage = sendClientService.findByPage(pageNum,pageSize);
        count = bypage.getTotalPages();
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("data",bypage);
        map.put("pageNum",pageNum);
        return map;
    }
}
